<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'
import { usePlugin } from '../../compositions/usePlugins'
import { addPositons, getNearbyPositions } from '../../composition/map'
import useUser from '../../composition/useUser'
import { showToast } from 'vant'
import router from '../../plugins/router'

window._AMapSecurityConfig = {
   securityJsCode: 'e04c198ab72411ec8f108b4f65cfa941' // 不建议这么写，不安全。我只是方便演示
}

const map = ref<any>()

const { addLocation } = useUser()

const userInfo = ref<null | UserModel>(JSON.parse(localStorage.getItem('userInfo') || 'null'))

let AMaps: any

const distance = ref<number>()

const position = ref<[number, number]>()

const initMap = () => {
   AMapLoader.load({
      key: 'efa469855021380b270d58ba3d87e2d5',
      version: '2.0'
   })
      .then(async (AMap: any) => {
         AMaps = AMap
         map.value = new AMap.Map('container', {
            viewMode: '3D', // 是否为3D地图模式
            zoom: 15 // 初始化地图级别
         })

         const { addGeolocation } = usePlugin(map.value, AMap)
         const pos = await addGeolocation()

         if (!pos) return alert('获取位置失败')
         position.value = [pos.longitude, pos.latitude]
         // 如果disstate不为空，说明已经获取过位置信息不需要再次添加
         if (!distance.value) {
            // 将位置信息添加到redis中
            if (!userInfo.value) {
               router.push({ name: 'login' })
               return showToast('请先登录')
            }
            await addPositons({
               userId: userInfo.value?.id,
               longitude: pos.longitude,
               latitude: pos.latitude
            })
            // 将位置添加到数据库
            await addLocation({
               longitude: pos.longitude,
               latitude: pos.latitude,
            })
         }

         // 获取附近位置信息
         const locationList = await getNearbyPositions({
            longitude: position.value[0],
            latitude: position.value[1],
            radius: distance.value ? distance.value : 1
         })

         // 添加标记
         locationList.data.data.forEach((item: any) => {
            const marker = new AMaps.Marker({
               icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
               position: new AMap.LngLat(item.longitude, item.latitude)
            })
            map.value.add(marker)
            marker.setExtData({
               data: item
            })
            marker.on('click', (e: Record<string, any>) => {
               const id = e.target.getExtData().data.name
               router.push({ name: 'me.article', params: { userId: +id } })
            })
         })
      })
      .catch((e: Error) => {
         console.log(e)
      })
}

const search = async () => {
   if (!distance.value) return alert('请输入范围')
   if (!position.value) return alert('请重新获取位置')
   initMap()
}

onMounted(() => {
   initMap()

})

onUnmounted(() => {
   map.value?.destroy()

})
</script>

<template>
   <div class="main">
      <div id="container" class="container"></div>
      <div class="header">
         <div class="search-container">
            <input type="text" class="search-input" placeholder="输入范围(KM)" v-model="distance" />
         </div>
         <div class="search-btn" @click="search">
            <img src="../../../public/search.png" alt="" />
         </div>
      </div>
   </div>
</template>

<style scoped>
#container {
   width: 100%;
   height: 100vh;
}

* {
   box-sizing: border-box;
}

body {
   font-family: Arial, sans-serif;
   margin: 0;
   padding: 0;
}

.header {
   position: fixed;
   top: 0;
   left: 0;
   z-index: 999;
   height: 64px;
   display: flex;
   align-items: center;
   justify-content: space-between;
   width: 100%;
   padding: 20px;
}

.search-container {
   position: relative;
   width: 85%;
   max-width: 800px;
   margin: 0 auto;
   z-index: 9999;
}

.search-input {
   width: 100%;
   height: 40px;
   padding: 0 40px 0 20px;
   font-size: 16px;
   border: none;
   outline: none;
   border-radius: 20px;
   background-color: #fff;
   transition: background-color 0.3s ease;
}

.search-btn {
   height: 36px;
   width: 36px;
   border: none;
   outline: none;
   background-color: #0078d4;
   cursor: pointer;
   border-radius: 50%;
   display: flex;
   align-items: center;
   justify-content: center;
   font-size: 11px;
   color: #fff;
   margin-top: 5px;

   img {
      width: 16px;
      height: 16px;
   }
}

.search-input:focus {
   background-color: #e0e0e0;
}
</style>
